<template>
  <div>
    <Divider orientation="right">
      <Select v-model="selectedUid" style="width:120px; float: right;">
        <Option v-for="uid in uids" :value="uid" :key="uid">{{ uid }}</Option>
      </Select>
    </Divider>
    <Table
      @on-selection-change="handleChange"
      border
      :loading="loading"
      stripe
      :columns="columns1"
      :data="books"
    >
      <template slot-scope="{ row, index }" slot="action">
        <div>
          <Button @click="handleDelete(row, index)">删除</Button>
        </div>
      </template>
    </Table>
    <Divider orientation="right">
      <Button
        style="width: 120px;"
        @click="handleDeleteAll"
        :disabled="selectedBooks.length === 0"
      >删除选中</Button>
    </Divider>
  </div>
</template>

<script>
import { getAllUids, getAllBooksByUid, deleteBooksByUid } from "../api/lbooks";
export default {
  name: "cloudBook",

  data() {
    return {
      books: [],
      selectedBooks: [],
      selectedUid: "",
      uids: [],
      loading: false,
      columns1: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "Name",
          key: "title"
        },
        {
          title: "Action",
          key: "action",
          slot: "action"
          // render: this.renderDownloadButton
        }
      ],
      loading: false
    };
  },

  mounted() {
    this.init();
  },

  watch: {
    selectedUid() {
      this.fetchAllBooks(this.selectedUid);
    }
  },

  methods: {
    async init() {
      await this.fetchAllUids();
    },

    async fetchAllBooks(uid) {
      this.loading = true;
      const res = await getAllBooksByUid(uid);
      this.books = res.data;
      this.loading = false;
    },

    async fetchAllUids() {
      this.loading = true;
      const res = await getAllUids();
      this.uids = res.data;
      this.loading = false;
    },

    async handleDelete(row) {
      this.loading = true;
      await deleteBooksByUid(this.selectedUid, [row.bid]);
      this.$Notice.success({
        title: "删除成功!",
        desc: `${row.title} 删除成功!`,
        duration: 5
      });
      await this.fetchAllBooks(this.selectedUid);
      this.loading = false;
    },

    async handleDeleteAll() {
      this.loading = true;
      await deleteBooksByUid(
        this.selectedUid,
        this.selectedBooks.map(b => b.bid)
      );
      this.$Notice.success({
        title: "删除成功!",
        desc: `${this.selectedBooks.length}本书籍删除成功!`,
        duration: 5
      });
      this.selectedBooks = []
      await this.fetchAllBooks(this.selectedUid);
      this.loading = false;
    },

    handleChange(selection) {
      this.selectedBooks = selection;
    }
  }
};
</script>

<style scoped>
</style>